import mammoth from 'mammoth';

// 将 DOC 文件转换为 Tiptap JSON 格式
export const convertDocToTiptap = async (file) => {
  try {
    // 使用 mammoth 解析 DOC 文件
    const result = await mammoth.convertToHtml({ arrayBuffer: await file.arrayBuffer() });
    const html = result.value;
    
    // 将 HTML 转换为 Tiptap JSON 格式
    const tiptapJson = convertHtmlToTiptap(html);
    
    return tiptapJson;
  } catch (error) {
    console.error('文档转换失败:', error);
    throw new Error('文档解析失败，请检查文件格式');
  }
};

// 将 HTML 转换为 Tiptap JSON 格式
const convertHtmlToTiptap = (html) => {
  // 创建临时 DOM 元素来解析 HTML
  const parser = new DOMParser();
  const doc = parser.parseFromString(html, 'text/html');
  
  const content = [];
  
  // 遍历所有子节点
  Array.from(doc.body.childNodes).forEach(node => {
    const element = convertNodeToTiptap(node);
    if (element) {
      content.push(element);
    }
  });
  
  return {
    type: "doc",
    content: content
  };
};

// 转换单个节点
const convertNodeToTiptap = (node) => {
  if (node.nodeType === Node.TEXT_NODE) {
    const text = node.textContent.trim();
    if (text) {
      return {
        type: "text",
        text: text
      };
    }
    return null;
  }
  
  if (node.nodeType === Node.ELEMENT_NODE) {
    const tagName = node.tagName.toLowerCase();
    
    switch (tagName) {
      case 'h1':
      case 'h2':
      case 'h3':
      case 'h4':
      case 'h5':
      case 'h6':
        return convertHeading(node);
        
      case 'p':
        return convertParagraph(node);
        
      case 'blockquote':
        return convertBlockquote(node);
        
      case 'pre':
        return convertCodeBlock(node);
        
      case 'ul':
      case 'ol':
        return convertList(node);
        
      case 'table':
        return convertTable(node);
        
      case 'hr':
        return { type: "horizontalRule" };
        
      case 'img':
        return convertImage(node);
        
      case 'div':
        return convertDiv(node);
        
      default:
        return convertParagraph(node);
    }
  }
  
  return null;
};

// 转换标题
const convertHeading = (element) => {
  const level = parseInt(element.tagName.charAt(1));
  const content = convertInlineContent(element);
  
  return {
    type: "heading",
    attrs: {
      textAlign: getTextAlign(element),
      level: level
    },
    content: content
  };
};

// 转换段落
const convertParagraph = (element) => {
  const content = convertInlineContent(element);
  
  return {
    type: "paragraph",
    attrs: {
      textAlign: getTextAlign(element)
    },
    content: content
  };
};

// 转换引用块
const convertBlockquote = (element) => {
  const content = [];
  
  Array.from(element.childNodes).forEach(child => {
    if (child.tagName === 'P') {
      const paragraph = convertParagraph(child);
      content.push(paragraph);
    }
  });
  
  return {
    type: "blockquote",
    content: content
  };
};

// 转换代码块
const convertCodeBlock = (element) => {
  const text = element.textContent || '';
  
  return {
    type: "codeBlock",
    attrs: {
      language: null
    },
    content: [
      {
        type: "text",
        text: text
      }
    ]
  };
};

// 转换列表
const convertList = (element) => {
  const isOrdered = element.tagName === 'OL';
  const listType = isOrdered ? "orderedList" : "bulletList";
  const content = [];
  
  Array.from(element.children).forEach(li => {
    if (li.tagName === 'LI') {
      const listItem = {
        type: "listItem",
        content: []
      };
      
      Array.from(li.childNodes).forEach(child => {
        if (child.tagName === 'P') {
          const paragraph = convertParagraph(child);
          listItem.content.push(paragraph);
        } else if (child.nodeType === Node.TEXT_NODE) {
          const text = child.textContent.trim();
          if (text) {
            listItem.content.push({
              type: "paragraph",
              attrs: { textAlign: null },
              content: [{ type: "text", text: text }]
            });
          }
        }
      });
      
      content.push(listItem);
    }
  });
  
  return {
    type: listType,
    content: content
  };
};

// 转换任务列表
const convertTaskList = (element) => {
  const content = [];
  
  Array.from(element.children).forEach(li => {
    if (li.tagName === 'LI') {
      const isChecked = li.getAttribute('data-checked') === 'true' || 
                       li.querySelector('input[type="checkbox"]')?.checked;
      
      const taskItem = {
        type: "taskItem",
        attrs: {
          checked: isChecked
        },
        content: []
      };
      
      Array.from(li.childNodes).forEach(child => {
        if (child.tagName === 'P') {
          const paragraph = convertParagraph(child);
          taskItem.content.push(paragraph);
        } else if (child.nodeType === Node.TEXT_NODE) {
          const text = child.textContent.trim();
          if (text) {
            taskItem.content.push({
              type: "paragraph",
              attrs: { textAlign: null },
              content: [{ type: "text", text: text }]
            });
          }
        }
      });
      
      content.push(taskItem);
    }
  });
  
  return {
    type: "taskList",
    content: content
  };
};

// 转换表格
const convertTable = (element) => {
  const content = [];
  
  Array.from(element.children).forEach(row => {
    if (row.tagName === 'TR') {
      const tableRow = {
        type: "tableRow",
        content: []
      };
      
      Array.from(row.children).forEach(cell => {
        if (cell.tagName === 'TD' || cell.tagName === 'TH') {
          const tableCell = {
            type: "tableCell",
            attrs: {},
            content: convertInlineContent(cell)
          };
          tableRow.content.push(tableCell);
        }
      });
      
      content.push(tableRow);
    }
  });
  
  return {
    type: "table",
    content: content
  };
};

// 转换图片
const convertImage = (element) => {
  return {
    type: "image",
    attrs: {
      src: element.src || "",
      alt: element.alt || "",
      title: element.title || ""
    }
  };
};

// 转换 div
const convertDiv = (element) => {
  const content = convertInlineContent(element);
  
  if (content.length === 0) return null;
  
  return {
    type: "paragraph",
    attrs: {
      textAlign: getTextAlign(element)
    },
    content: content
  };
};

// 转换内联内容（文本、链接、格式化等）
const convertInlineContent = (element) => {
  const content = [];
  
  Array.from(element.childNodes).forEach(child => {
    if (child.nodeType === Node.TEXT_NODE) {
      const text = child.textContent;
      if (text) {
        content.push({
          type: "text",
          text: text
        });
      }
    } else if (child.nodeType === Node.ELEMENT_NODE) {
      const inlineElement = convertInlineElement(child);
      if (inlineElement) {
        content.push(inlineElement);
      }
    }
  });
  
  return content;
};

// 转换内联元素
const convertInlineElement = (element) => {
  const tagName = element.tagName.toLowerCase();
  const text = element.textContent || '';
  
  if (!text) return null;
  
  const marks = [];
  
  // 处理文本格式 - 支持所有工具栏格式
  switch (tagName) {
    case 'strong':
    case 'b':
      marks.push({ type: "bold" });
      break;
      
    case 'em':
    case 'i':
      marks.push({ type: "italic" });
      break;
      
    case 'u':
      marks.push({ type: "underline" });
      break;
      
    case 's':
    case 'strike':
      marks.push({ type: "strike" });
      break;
      
    case 'sub':
      marks.push({ type: "subscript" });
      break;
      
    case 'sup':
      marks.push({ type: "superscript" });
      break;
      
    case 'code':
      marks.push({ type: "code" });
      break;
      
    case 'a':
      marks.push({
        type: "link",
        attrs: {
          href: element.href || "",
          target: "_blank",
          rel: "noopener noreferrer nofollow",
          class: null
        }
      });
      break;
      
    case 'mark':
      marks.push({
        type: "highlight",
        attrs: {
          color: "var(--tt-color-highlight-yellow)"
        }
      });
      break;
  }
  
  // 处理文本颜色
  if (element.style && element.style.color) {
    marks.push({
      type: "textStyle",
      attrs: {
        color: element.style.color
      }
    });
  }
  
  // 处理背景色（高亮）
  if (element.style && element.style.backgroundColor) {
    const bgColor = element.style.backgroundColor;
    // 将颜色值转换为 CSS 变量格式
    const highlightColor = convertColorToHighlightVar(bgColor);
    marks.push({
      type: "highlight",
      attrs: {
        color: highlightColor
      }
    });
  }
  
  // 处理字体大小
  if (element.style && element.style.fontSize) {
    marks.push({
      type: "textStyle",
      attrs: {
        fontSize: element.style.fontSize
      }
    });
  }
  
  return {
    type: "text",
    text: text,
    marks: marks.length > 0 ? marks : undefined
  };
};

// 将颜色值转换为高亮 CSS 变量
const convertColorToHighlightVar = (color) => {
  // 颜色映射表
  const colorMap = {
    '#ffcdd2': 'var(--tt-color-highlight-red)',
    '#ffe0b2': 'var(--tt-color-highlight-orange)',
    '#fff9c4': 'var(--tt-color-highlight-yellow)',
    '#c8e6c9': 'var(--tt-color-highlight-green)',
    '#bbdefb': 'var(--tt-color-highlight-blue)',
    '#e1bee7': 'var(--tt-color-highlight-purple)',
    '#f8bbd9': 'var(--tt-color-highlight-pink)',
    '#f5f5f5': 'var(--tt-color-highlight-gray)',
    '#d7ccc8': 'var(--tt-color-highlight-brown)',
    '#ff0000': 'var(--tt-color-highlight-red)',
    '#ffa500': 'var(--tt-color-highlight-orange)',
    '#ffff00': 'var(--tt-color-highlight-yellow)',
    '#00ff00': 'var(--tt-color-highlight-green)',
    '#0000ff': 'var(--tt-color-highlight-blue)',
    '#800080': 'var(--tt-color-highlight-purple)',
    '#ffc0cb': 'var(--tt-color-highlight-pink)',
    '#808080': 'var(--tt-color-highlight-gray)',
    '#a52a2a': 'var(--tt-color-highlight-brown)',
  };
  
  // 尝试精确匹配
  if (colorMap[color.toLowerCase()]) {
    return colorMap[color.toLowerCase()];
  }
  
  // 尝试 RGB 格式匹配
  const rgbMatch = color.match(/rgb\((\d+),\s*(\d+),\s*(\d+)\)/);
  if (rgbMatch) {
    const r = parseInt(rgbMatch[1]);
    const g = parseInt(rgbMatch[2]);
    const b = parseInt(rgbMatch[3]);
    
    // 简单的颜色分类逻辑
    if (r > 200 && g < 100 && b < 100) return 'var(--tt-color-highlight-red)';
    if (r > 200 && g > 150 && b < 100) return 'var(--tt-color-highlight-orange)';
    if (r > 200 && g > 200 && b < 100) return 'var(--tt-color-highlight-yellow)';
    if (r < 100 && g > 150 && b < 100) return 'var(--tt-color-highlight-green)';
    if (r < 100 && g < 150 && b > 200) return 'var(--tt-color-highlight-blue)';
    if (r > 150 && g < 100 && b > 150) return 'var(--tt-color-highlight-purple)';
    if (r > 200 && g < 150 && b > 150) return 'var(--tt-color-highlight-pink)';
    if (r > 150 && g > 150 && b > 150) return 'var(--tt-color-highlight-gray)';
  }
  
  // 默认返回黄色高亮
  return 'var(--tt-color-highlight-yellow)';
};

// 获取文本对齐方式
const getTextAlign = (element) => {
  const style = element.style || {};
  const textAlign = style.textAlign || element.getAttribute('align');
  
  if (textAlign === 'center') return 'center';
  if (textAlign === 'right') return 'right';
  if (textAlign === 'justify') return 'justify';
  
  return 'left';
};